<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { 
  getTransactionOverview, 
  getTransactionTrend, 
  getOrderDetailList, 
  getRefundDetailList 
} from '@/api/system/orderStatistic'
import * as echarts from 'echarts'

// 响应式数据
const activeDateType = ref('7') // 默认选择过去7天
const activeTab = ref('order') // 默认选择订单标签
const yearMonth = ref('2025-08')
const transactionOverview = ref({})
const tableData = ref([])
const trendChartRef = ref(null)
let trendChart = null

// 日期选项
const dateOptions = reactive([
  { label: '今天', value: '1' },
  { label: '昨天', value: '2' },
  { label: '过去7天', value: '7' },
  { label: '过去30天', value: '30' }
])

// 处理日期变化
const handleDateChange = (dateType) => {
  activeDateType.value = dateType
  loadAllData()
}

// 处理标签页变化
const handleTabChange = (tab) => {
  activeTab.value = tab
  loadTableData()
}

// 加载所有数据
const loadAllData = async () => {
  await Promise.all([
    loadTransactionOverview(),
    loadTransactionTrend(),
    loadTableData()
  ])
}

// 加载交易概况数据
const loadTransactionOverview = async () => {
  try {
    const params = {
      dateType: activeDateType.value,
      businessId: null
    }
    const response = await getTransactionOverview(params)
    if (response.code === 200) {
      transactionOverview.value = response.data || {}
    }
  } catch (error) {
    console.error('获取交易概况失败:', error)
  }
}

// 加载交易趋势数据
const loadTransactionTrend = async () => {
  try {
    const params = {
      dateType: activeDateType.value,
      businessId: null
    }
    const response = await getTransactionTrend(params)
    if (response.code === 200) {
      renderTrendChart(response.data || [])
    }
  } catch (error) {
    console.error('获取交易趋势失败:', error)
  }
}

// 加载表格数据
const loadTableData = async () => {
  try {
    const params = {
      dateType: activeDateType.value,
      businessId: null,
      limit: 20
    }
    
    let response
    if (activeTab.value === 'order') {
      response = await getOrderDetailList(params)
    } else {
      response = await getRefundDetailList(params)
    }
    
    if (response.code === 200) {
      tableData.value = response.data || []
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  }
}

// // 渲染趋势图
// const renderTrendChart = (data) => {
//   if (!trendChartRef.value) return
//
//   if (!trendChart) {
//     trendChart = echarts.init(trendChartRef.value)
//   }
//
//   const dates = data.map(item => item.dateStr)
//   const amounts = data.map(item => parseFloat(item.transactionAmount || 0))
//
//   const option = {
//     title: {
//       text: '交易趋势',
//       left: 'left',
//       textStyle: {
//         fontSize: 16,
//         fontWeight: 'bold'
//       }
//     },
//     tooltip: {
//       trigger: 'axis',
//       formatter: function(params) {
//         return `${params[0].name}<br/>交易额: ¥${formatAmount(params[0].value)}`
//       }
//     },
//     xAxis: {
//       type: 'category',
//       data: dates,
//       axisLabel: {
//         rotate: 45
//       }
//     },
//     yAxis: {
//       type: 'value',
//       axisLabel: {
//         formatter: function(value) {
//           return value.toLocaleString()
//         }
//       }
//     },
//     series: [{
//       name: '交易额',
//       type: 'line',
//       data: amounts,
//       smooth: true,
//       lineStyle: {
//         color: '#409eff'
//       },
//       itemStyle: {
//         color: '#409eff'
//       },
//       areaStyle: {
//         color: {
//           type: 'linear',
//           x: 0,
//           y: 0,
//           x2: 0,
//           y2: 1,
//           colorStops: [{
//             offset: 0, color: 'rgba(64, 158, 255, 0.3)'
//           }, {
//             offset: 1, color: 'rgba(64, 158, 255, 0.1)'
//           }]
//         }
//       }
//     }]
//   }
//
//   trendChart.setOption(option)
// }
const option = {
  xAxis: {
    text: "交易趋势",
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [820, 932, 901, 934, 1290, 1330, 1320],
      type: 'line',
      smooth: true
    }
  ]
};

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return parseFloat(amount).toFixed(2)
}

// 格式化转化率
const formatRate = (rate) => {
  if (!rate) return '0.00'
  return parseFloat(rate).toFixed(2)
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case '已完成':
      return 'status-success'
    case '已发货':
      return 'status-info'
    case '已支付':
      return 'status-warning'
    case '已取消':
      return 'status-danger'
    default:
      return 'status-default'
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadAllData()
  
  // 监听窗口大小变化，重新渲染图表
  window.addEventListener('resize', () => {
    if (trendChart) {
      trendChart.resize()
    }
  })
})
</script>

<template>
  <div class="app-container">
    <!-- 顶部筛选区域 -->
    <div class="filter-container">
      <div class="date-filter">
        <span 
          v-for="item in dateOptions" 
          :key="item.value"
          :class="['date-option', { active: activeDateType === item.value }]"
          @click="handleDateChange(item.value)"
        >
          {{ item.label }}
        </span>
      </div>
      <div class="year-month-filter">
        <el-select v-model="yearMonth" placeholder="年月查询" style="width: 120px">
          <el-option label="2025年8月" value="2025-08" />
          <el-option label="2025年7月" value="2025-07" />
          <el-option label="2025年6月" value="2025-06" />
        </el-select>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧交易概况 -->
      <div class="left-panel">
        <div class="panel-title">交易概况</div>
        
        <!-- 转换部分 -->
        <div class="section">
          <div class="section-title">转换</div>
          <div class="metrics-grid">
            <div class="metric-item">
              <div class="metric-label">访客数UV</div>
              <div class="metric-value">{{ transactionOverview.visitorUV || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">下单转化率</div>
              <div class="metric-value">{{ formatRate(transactionOverview.orderConversionRate) }}%</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">付款转化率</div>
              <div class="metric-value">{{ formatRate(transactionOverview.paymentConversionRate) }}%</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">全店转化率</div>
              <div class="metric-value">{{ formatRate(transactionOverview.overallConversionRate) }}%</div>
            </div>
          </div>
        </div>

        <!-- 订单部分 -->
        <div class="section">
          <div class="section-title">订单</div>
          <div class="metrics-grid">
            <div class="metric-item">
              <div class="metric-label">下单笔数</div>
              <div class="metric-value">{{ transactionOverview.orderCount || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">下单人数</div>
              <div class="metric-value">{{ transactionOverview.orderUserCount || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">下单金额</div>
              <div class="metric-value">¥{{ formatAmount(transactionOverview.orderAmount) }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">付款笔数</div>
              <div class="metric-value">{{ transactionOverview.paymentCount || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">付款人数</div>
              <div class="metric-value">{{ transactionOverview.paymentUserCount || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">付款金额</div>
              <div class="metric-value">¥{{ formatAmount(transactionOverview.paymentAmount) }}</div>
            </div>
          </div>
        </div>

        <!-- 退单部分 -->
        <div class="section">
          <div class="section-title">退单</div>
          <div class="metrics-grid">
            <div class="metric-item">
              <div class="metric-label">退单笔数</div>
              <div class="metric-value">{{ transactionOverview.refundCount || 0 }}</div>
            </div>
            <div class="metric-item">
              <div class="metric-label">退单金额</div>
              <div class="metric-value">¥{{ formatAmount(transactionOverview.refundAmount) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧漏斗图 -->
      <div class="right-panel">
        <div class="funnel-chart">
          <div class="funnel-item visitor">
            <div class="funnel-label">访客数</div>
            <div class="funnel-value">{{ transactionOverview.visitorUV || 0 }}</div>
          </div>
          <div class="funnel-connection">
            <div class="connection-line left">
              <span class="rate-label">下单转化率</span>
              <span class="rate-value">{{ formatRate(transactionOverview.orderConversionRate) }}%</span>
            </div>
            <div class="connection-line right">
              <span class="rate-label">整体转换率</span>
              <span class="rate-value">{{ formatRate(transactionOverview.overallConversionRate) }}%</span>
            </div>
          </div>
          <div class="funnel-item order">
            <div class="funnel-label">下单笔数</div>
            <div class="funnel-value">{{ transactionOverview.orderCount || 0 }}</div>
          </div>
          <div class="funnel-connection">
            <div class="connection-line left">
              <span class="rate-label">付款转化率</span>
              <span class="rate-value">{{ formatRate(transactionOverview.paymentConversionRate) }}%</span>
            </div>
          </div>
          <div class="funnel-item payment">
            <div class="funnel-label">付款笔数</div>
            <div class="funnel-value">{{ transactionOverview.paymentCount || 0 }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 交易趋势图 -->
    <div class="trend-chart-container">
      <e-charts class="chart1" :option="option"/>
    </div>

    <!-- 订退单统计 -->
    <div class="order-refund-container">
      <div class="tab-header">
        <span 
          :class="['tab-item', { active: activeTab === 'order' }]"
          @click="handleTabChange('order')"
        >
          订单
        </span>
        <span 
          :class="['tab-item', { active: activeTab === 'refund' }]"
          @click="handleTabChange('refund')"
        >
          退单
        </span>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table 
          :data="tableData" 
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column prop="businessName" label="商家名称" width="150">
            <template #default="scope">
              <span>{{ scope.row.businessName || '杂货铺' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="用户名" width="200">
            <template #default="scope">
              <span>{{ scope.row.userName || '未知用户' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" width="120" align="center">
            <template #default="scope">
              <span :class="getStatusClass(scope.row.orderStatus)">{{ scope.row.orderStatus }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="scope">
              <span>{{ formatDateTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="payTime" label="支付时间" width="180">
            <template #default="scope">
              <span>{{ scope.row.payTime ? formatDateTime(scope.row.payTime) : '暂无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="120" align="center">
            <template #default="scope">
              <span class="price-text">¥{{ formatAmount(scope.row.price) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.date-filter {
  display: flex;
  gap: 20px;
}

.date-option {
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
  font-size: 14px;
  color: #606266;
  
  &:hover {
    background: #f5f7fa;
  }
  
  &.active {
    color: #f56c6c;
    background: #fef0f0;
    border-bottom: 2px solid #f56c6c;
  }
}

.year-month-filter {
  .el-select {
    .el-input__inner {
      border-radius: 4px;
    }
  }
}

.main-content {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.left-panel {
  flex: 1;
  background: #fafafa;
  border-radius: 8px;
  padding: 20px;
}

.panel-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.section {
  margin-bottom: 25px;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #606266;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.metric-item {
  background: #fff;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.metric-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.right-panel {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.funnel-chart {
  width: 100%;
  max-width: 400px;
}

.funnel-item {
  background: #f56c6c;
  color: white;
  padding: 20px;
  margin: 10px 0;
  border-radius: 8px;
  text-align: center;
  position: relative;
  
  &.visitor {
    background: #f56c6c;
  }
  
  &.order {
    background: #e6a23c;
    margin-left: 20px;
    margin-right: 20px;
  }
  
  &.payment {
    background: #67c23a;
    margin-left: 40px;
    margin-right: 40px;
  }
}

.funnel-label {
  font-size: 14px;
  margin-bottom: 5px;
}

.funnel-value {
  font-size: 24px;
  font-weight: bold;
}

.funnel-connection {
  position: relative;
  height: 30px;
}

.connection-line {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  
  &.left {
    left: 10px;
  }
  
  &.right {
    right: 10px;
  }
}

.rate-label {
  display: block;
  font-size: 10px;
  color: #909399;
}

.rate-value {
  display: block;
  font-size: 12px;
  color: #f56c6c;
  font-weight: bold;
}

.trend-chart-container {
  margin-bottom: 30px;
}

.chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.chart-content {
  height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.order-refund-container {
  .tab-header {
    display: flex;
    border-bottom: 1px solid #ebeef5;
    margin-bottom: 20px;
  }

  .tab-item {
    padding: 12px 24px;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    transition: all 0.3s;
    font-size: 14px;
    color: #606266;
    
    &:hover {
      color: #f56c6c;
    }
    
    &.active {
      color: #f56c6c;
      border-bottom-color: #f56c6c;
    }
  }
}

.table-container {
  .el-table {
    border-radius: 8px;
    overflow: hidden;
    
    .el-table__header {
      th {
        font-weight: 600;
      }
    }
    
    .el-table__body {
      td {
        padding: 12px 0;
      }
    }
  }
}

.price-text {
  font-weight: 600;
  color: #f56c6c;
}

.status-success {
  color: #67c23a;
  font-weight: 600;
}

.status-info {
  color: #409eff;
  font-weight: 600;
}

.status-warning {
  color: #e6a23c;
  font-weight: 600;
}

.status-danger {
  color: #f56c6c;
  font-weight: 600;
}

.status-default {
  color: #909399;
  font-weight: 600;
}
</style>